/**
 * @说明: 地图数据, 用于存储地图数据及监听地图数据变化
 */
export class MapData {
  constructor(data) {
    this.data = {};
    this.data = this.GetData(data);
    this.selected = { index: -1, stage: null };
    this.listeners = {};
  }

  /** @辅助 更新数据 */
  GetData(data) {
    return {
      scale: {
        min: 1,
        max: 10,
        step: 0.2,
        scaling: 1,
        ...this.data.scale,
        ...(data.scale || {}),
      },
      stages: [
        ...(data.stages || []).map((v) => {
          const stages = ({ polygon: [], ...v });
          stages.polygon = (v.polygon || []).map((point) => {
            if (typeof point === 'object') {
              return { ...point };
            }
            const [x, y] = point.split(',').map(v => parseFloat(v));
            return { x, y };
          });
          return stages;
        }),
      ],
      wrapper: {
        lineWidth: 2,
        lineColor: 'rgba(255,255,255,0.5)',
        backgroundColor: 'rgba(0,0,0,0.5)',
        ...this.data.wrapper,
        ...(data.wrapper || {}),
      },
      background: {
        src: '',
        width: 0,
        height: 0,
        offsetX: 0,
        offsetY: 0,
        ...this.data.background,
        ...(data.background || {}),
      }
    };
  }

  /** @方法 获取事件 */
  getListeners(type) {
    !this.listeners[type] && (this.listeners[type] = []);
    return this.listeners[type];
  }
  
  /** @方法 监听事件 */
  addListener(type, listener) {
    this.getListeners(type).push(listener);
    if (type === 'data') {
      listener(this.data);
    } else if (type === 'selected') {
      listener(this.selected);
    }
  }

  /** @方法 触发监听 */
  dispatch(type, ...args) {
    if ('data' === type) {
      this.data = args[0];
    } else if ('selected' === type) {
      this.selected = args[0];
    } else if ('data:stages' === type) {
      this.data.stages = args[0]; type = 'data';
    }
    if ('data' === type) {
      this.getListeners(type).forEach((listener) => listener(this.data));
    } else if ('selected' === type) {
      this.getListeners(type).forEach((listener) => listener(this.selected));
    }
  }

  /** @方法 转换存储 */
  toObject() {
    const data = this.data;
    return {
      scale: { ...data.scale },
      stages: [
        ...data.stages.map((v) => {
          const stages = ({ polygon: [], ...v });
          stages.polygon = (v.polygon || []).map(({ x, y }) => `${x},${y}`);
          return stages;
        }),
      ],
      wrapper: { ...data.wrapper },
      background: { ...data.background },
    };
  }

  /** @方法 转换Json */
  toJson() {
    return JSON.stringify(this.toObject());
  }

  /** @方法 销毁监听 */
  destroy() {
    this.listeners = { data: [], selected: [] };
  }
}
export default MapData;
